const fs = require('fs');
const path = require('path');
const archiver = require('archiver'); // eslint-disable-line
const { exec } = require('child_process');

const releaseFolder = 'release';

async function main() {
  function getYMDHMS() {
    const pad = (n, c = '0') => {
      const p = s => {
        const t = String(s);
        return t.length >= n ? t : p(c + t, n, c);
      };
      return p;
    };
    const date = new Date();
    const y = date.getFullYear();
    const m = date.getMonth() + 1;
    const d = date.getDate();
    const h = date.getHours();
    const mm = date.getMinutes();
    return [y, m, d, h, mm].map(pad(2)).join('');
  }

  async function getGitBranchName() {
    const name = await new Promise((resolve, reject) => {
      exec('git rev-parse --abbrev-ref HEAD', (error, stdout, stderr) => {
        if (error) {
          resolve('');
          console.error(stderr);
        } else {
          resolve(stdout.trim());
        }
      });
    });
    return name;
  }

  async function getOutputZipFile() {
    const npmLifeCycle = process.env.npm_lifecycle_event;
    let env = process.env.NODE_ENV;
    if (npmLifeCycle) {
      const [, environment] = npmLifeCycle.split(':');
      if (environment) {
        env = environment;
      }
    }
    const branchName = await getGitBranchName();
    if (env === 'prod' && branchName !== 'master') {
      console.warn(
        '\x1b[31m%s\n\x1b[0m',
        `打包的环境为生产环境(${env}), 但分支(${branchName})不是master分支，请留意。`
      );
    }
    const name = [env, 'www_tnaot_com', getYMDHMS(), branchName].join('_');
    return path.join(__dirname, 'release', `${name}.zip`);
  }

  const outputZipFile = await getOutputZipFile();

  function size(bytes) {
    const units = [
      ['B', 1],
      ['K', 1024],
      ['M', 1024],
      ['G', 1024]
    ];
    let result = '';
    while (bytes && units.length) {
      let scale = 1;
      for (let i = 0; i < units.length; i += 1) {
        scale *= units[i][1];
      }
      const factor = bytes / scale;
      const intFactor = Math.floor(factor);
      if (intFactor > 0) {
        result += `${factor.toFixed(2)}${units[units.length - 1][0]}`;
        break;
      }
      bytes -= intFactor * scale; // eslint-disable-line
      units.pop();
    }
    return result;
  }

  if (fs.existsSync(outputZipFile)) {
    fs.unlinkSync(outputZipFile);
  }

  if (!fs.existsSync(releaseFolder)) {
    fs.mkdirSync(path.join(__dirname, releaseFolder));
  }

  const output = fs.createWriteStream(outputZipFile);
  const archive = archiver('zip', {
    zlib: { level: 9 } // Sets the compression level.
  });

  // 'close' event is fired only when a file descriptor is involved
  output.on('close', () => {
    console.log(
      `压缩完成，文件：${path.basename(outputZipFile)}, 大小：${size(
        archive.pointer()
      )}`
    );
  });

  archive.on('warning', err => {
    if (err.code === 'ENOENT') {
      // log warning
    } else {
      // throw error
      throw err;
    }
  });

  archive.on('error', err => {
    throw err;
  });

  // pipe archive data to the file
  archive.pipe(output);
  archive.directory('.nuxt'); // false, putting its contents at the root of archive
  archive.directory('static');
  archive.directory('env');
  archive.file('nuxt.config.js');
  archive.file('package.json');
  archive.file('package-lock.json');
  archive.finalize();
}

main().catch(e => console.error(e));
